﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Reflection;

namespace YawetagLib.Data.L2EF
{
    public static class Extensions
    {
        public static IQueryable<TEntity> ToExtendedSet<TEntity>(this IQueryable<TEntity> dbSet) where TEntity : class
        {
            IEnumerable<string> propertyNames = GetIncludedPropertyNames<TEntity>();

            return propertyNames.Aggregate(dbSet, (current, i) => current.Include(i));
        }

        public static IEnumerable<string> GetIncludedPropertyNames<TEntity>()
        {
            return typeof(TEntity)
                .GetProperties()
                .Where(i => i.GetCustomAttributes(typeof(IncludeAttribute), true).Length == 1)
                .Select(i => i.Name);
        }

        public static bool IsDbContextEntityPrimaryKey<TEntity>(PropertyInfo propertyInfo)
        {
            object[] attributes = propertyInfo.GetCustomAttributes(typeof(KeyAttribute), true);

            if (attributes.Length != 1)
            {
                string propertyName = propertyInfo.Name.ToLower();
                return propertyName == "id" || propertyName == (typeof (TEntity).Name + "id").ToLower();
            }

            return true;
        }

        public static bool IsObjectContextEntityPrimaryKey(PropertyInfo propertyInfo)
        {
            object[] attributes = propertyInfo.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), true);
            EdmScalarPropertyAttribute primaryKeyAttribute = attributes.Length != 0 ? (EdmScalarPropertyAttribute)attributes[0] : null;

            return primaryKeyAttribute != null && primaryKeyAttribute.EntityKeyProperty;
        }
    }
}
